package day6.problem2;

import java.util.*;

//链表相加(二)
//https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=196&tqId=37147&ru=/exam/oj

class ListNode {
    int val;
    ListNode next = null;
    public ListNode(int val) {
      this.val = val;
    }
  }


public class Solution {
    public ListNode addInList (ListNode head1, ListNode head2) {
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode cur1 = head1, cur2 = head2;
        int t = 0;
        ListNode newHead = new ListNode(0);
        ListNode tail = newHead;
        while(cur1 != null || cur2 != null || t != 0) {
            int a = cur1 == null ? 0 : cur1.val;
            int b = cur2 == null ? 0 : cur2.val;
            int x = (a + b + t) % 10;
            t = (a + b + t) / 10;
            ListNode node = new ListNode(x);
            tail.next = node;
            tail = node;
            if(cur1 != null) cur1 = cur1.next;
            if(cur2 != null) cur2 = cur2.next;
        }
        newHead = reverse(newHead.next);
        return newHead;
    }

    public ListNode reverse(ListNode head) {
        ListNode newHead = new ListNode(0);
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = newHead.next;
            newHead.next = cur;
            cur = next;
        }
        return newHead.next;
    }
}